//
//  AppDelegate.m
//  demo
//
//  Created by God on 16/4/13.
//  Copyright © 2016年 N-wei. All rights reserved.
//

#import "AppDelegate.h"
#import "ViewController.h"
#import "NWloginViewController.h"
#import "JPUSHService.h"
#import "IQKeyboardManager.h"
#import <UserNotifications/UserNotifications.h>
#import "GMWebViewController.h"
#import "MBProgressHUD+GM.h"


#define USHARE_DEMO_APPKEY @"5811cb0b65b6d67cd8003bca"
@interface AppDelegate ()<UNUserNotificationCenterDelegate,JPUSHRegisterDelegate>
@property (nonatomic,assign)NSInteger jpushBadge;
@end

@implementation AppDelegate

- (void)dealloc
{
    [[UIApplication sharedApplication]setApplicationIconBadgeNumber:0];
    
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    static NSString *version = @"CFBundleVersion";
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *currentVersion = [NSBundle mainBundle].infoDictionary[version];
    NSString *lastVersion = [defaults valueForKey:version];
    
    //0 version check
    if (![lastVersion isEqualToString:currentVersion]) {
        ViewController *newFeatureVC = [[ViewController alloc]init];
        
        self.window.rootViewController = newFeatureVC;
        [defaults setValue:currentVersion forKeyPath:version];
    }else {
        NWloginViewController *HomeVc = [[NWloginViewController alloc]initWithNibName:@"NWloginViewController" bundle:nil];
        
        self.nav = [[UINavigationController alloc]initWithRootViewController:HomeVc];//先将root添加在navigation上

        self.window.rootViewController = self.nav;
    }
    [self.window makeKeyAndVisible];
    

    //Set key board
    [self setupKeyboard];
    
    //设置友盟统计
    //	[MobClick startWithAppkey:@"571f0559e0f55a14080011dc" reportPolicy:BATCH   channelId:nil];
    UMConfigInstance.appKey = USHARE_DEMO_APPKEY;
    UMConfigInstance.channelId = nil;
    //	UMConfigInstance.eSType = E_UM_GAME; //仅适用于游戏场景，应用统计不用设置
    [MobClick startWithConfigure:UMConfigInstance];//配置以上参数后调用此方法初始化SDK！
    
    [[UMSocialManager defaultManager] openLog:YES];
    
    //设置友盟分享
    [[UMSocialManager defaultManager] setUmSocialAppkey:USHARE_DEMO_APPKEY];
    [self configUSharePlatforms];
    
    //推送
    [self startJPUSHSeverWithOptions:launchOptions];
    
    //6 异常回调
    NSSetUncaughtExceptionHandler(&uncaughtExceptionHandler);
    
    return YES;
    
}




//或者APP不在前台时，接收到推送会有通知栏提示，这时点击通知栏唤醒（启动）APP，
-(void)startJPUSHSeverWithOptions:(NSDictionary *)launchOptions{
    
    // 启动极光推送
    
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) // iOS10
    {
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
        JPUSHRegisterEntity *entity = [[JPUSHRegisterEntity alloc] init];
        entity.types = (UNAuthorizationOptionAlert | UNAuthorizationOptionBadge | UNAuthorizationOptionSound);
        [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
#endif
    }
    else if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0)
    {
        // categories
        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert)
                                              categories:nil];
    }
    else
    {
        // categories nil
        [JPUSHService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)
                                              categories:nil];
        
    }
    
    //1.启动极光推送
    [JPUSHService setupWithOption:launchOptions appKey:JPUSH_KEY
                          channel:JPushChannel
                 apsForProduction:true
            advertisingIdentifier:nil];
    
    
    
    //2. 自定义消息只有APP在前台时才能接收到
    //    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    //    [defaultCenter addObserver:self selector:@selector(presentViewControllerWithPushInfo:) name:kJPFNetworkDidReceiveMessageNotification object:nil];
    
    
    
    
    
    //3. 2.1.9版本新增获取registration id block接口。
    [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
        if(resCode == 0)
        {
            // iOS10获取registrationID放到这里了, 可以存到缓存里, 用来标识用户单独发送推送
            NSLog(@"registrationID获取成功：%@",registrationID);
            [[NSUserDefaults standardUserDefaults] setObject:registrationID forKey:@"registrationID"];
            [[NSUserDefaults standardUserDefaults] synchronize];
        }
        else
        {
            NSLog(@"registrationID获取失败，code：%d",resCode);
        }
    }];
    
}


-(void)applicationWillResignActive:(UIApplication *)application {
    [JPUSHService setBadge:0];
    [[UIApplication sharedApplication]setApplicationIconBadgeNumber:0];
    
}

- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    /// Required -    DeviceToken
    
    //获取deviceToken
    NSString * tokenAsString = [[[deviceToken description]
                                 stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]]
                                stringByReplacingOccurrencesOfString:@" " withString:@""];
    LxDBAnyVar(tokenAsString);
    
    
    [JPUSHService registerDeviceToken:deviceToken];
}



-(void)tagsAliasCallback:(int)iResCode
                    tags:(NSSet*)tags
                   alias:(NSString*)alias
{
    NSLog(@"rescode: %d, \ntags: %@, \nalias: %@\n", iResCode, tags , alias);
}






#pragma mark- JPUSHRegisterDelegate
#pragma mark - iOS10: 收到推送消息调用(iOS10是通过Delegate实现的回调)

// iOS 10 Support
// 当程序在前台时, 收到推送弹出的通知

#ifdef NSFoundationVersionNumber_iOS_9_x_Max
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler
{
    //    NSDictionary *userInfo = [notification userInfo];
    
    NSDictionary *userInfo = notification.request.content.userInfo;
    
    LxDBAnyVar(userInfo);
    if ([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]])
    {
        [JPUSHService handleRemoteNotification:userInfo];
        
        //        [[[UIAlertView alloc] initWithTitle:@""
        //                                    message:@"有新消息是否查看"
        //                           cancelButtonItem:[RIButtonItem itemWithLabel:@"取消" action:^{}]
        //                           otherButtonItems:[RIButtonItem itemWithLabel:@"确定" action:^{
        //            [self presentViewControllerWithPushInfo:userInfo];
        //        }], nil] show];
        
        //        [MBProgressHUD showMessage:@"有新消息~"];
        [MBProgressHUD showMsgDelayHide:@"喂喂,有新消息~"];
        
    }
    
    
    // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以设置
    //         completionHandler(UNNotificationPresentationOptionBadge | UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert);
    
}

// 程序关闭后, 通过点击推送弹出的通知
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler
{
    NSDictionary *userInfo = response.notification.request.content.userInfo;
    
    if ([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]])
    {
        [JPUSHService handleRemoteNotification:userInfo];
        
        [self presentViewControllerWithPushInfo:userInfo];
    }
    
    //get  badge
    if ([userInfo isKindOfClass:[NSDictionary class]])
    {
        NSDictionary *dict = userInfo[@"aps"];
        self.jpushBadge = [dict[@"badge"] intValue];
        
        [JPUSHService setBadge:(self.jpushBadge-1)];
    }
    
    
    completionHandler();  // 系统要求执行这个方法
}
#endif



- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
    
    // apn 内容获取：
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
    
    //    if ([userInfo isKindOfClass:[NSDictionary class]])
    //    {
    //        NSDictionary *dict = userInfo[@"aps"];
    //        NSString *content = dict[@"alert"];
    //        LxDBAnyVar(content);
    //    }
    
    if (application.applicationState == UIApplicationStateActive)
    {
        // 程序当前正处于前台
    }
    else if (application.applicationState == UIApplicationStateInactive)
    {
        // 程序处于后台
        
    }
    
}



- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    // Required,For systems with less than or equal to iOS6
    [JPUSHService handleRemoteNotification:userInfo];
}







//====================For iOS 10====================



-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler{
    completionHandler(UNNotificationPresentationOptionAlert);
}

-(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)())completionHandler{
    UIApplication *applicaiton = [UIApplication sharedApplication];
    if (applicaiton.applicationState == UIApplicationStateActive) {
        NSString *string = response.notification.request.content.userInfo[@"aps"][@"alert"];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"推送消息" message:string delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alert show];
        
    }
    
}



- (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error
{
    LxDBAnyVar([error description]);
}





- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    /*
     // 这里是为了在点击icon图标使APP进入前台的情况下清除通知栏消息，可根据需求开启
     NSInteger badge = [UIApplication sharedApplication].applicationIconBadgeNumber;
     badge = badge == 1 ? 2 : 1;
     [UIApplication sharedApplication].applicationIconBadgeNumber = badge;
     */
    
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    [JPUSHService setBadge:(0)];
    
    
    //可以把 [JSPatch sync] 放在 -applicationDidBecomeActive: 里，每次唤醒都能同步更新 JSPatch 补丁，不需要等用户下次启动：
    
    
    
}


#pragma mark ---------------------method--------------------
/**
 *  异常回调
 *
 *  @param exception 异常信息
 */
void uncaughtExceptionHandler(NSException *exception) {
    
    LxDBAnyVar(exception);
    LxDBAnyVar( [exception callStackSymbols]);
    
}




/**
 * setup keyboard
 */
-(void)setupKeyboard{
    
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    manager.enable = YES;
    manager.shouldResignOnTouchOutside = YES;
    manager.shouldToolbarUsesTextFieldTintColor = YES;
    manager.enableAutoToolbar = NO;
    
    /*
     shouldResignOnTouchOutside控制点击背景是否收起键盘。
     shouldToolbarUsesTextFieldTintColor 控制键盘上的工具条文字颜色是否用户自定义。
     enableAutoToolbar控制是否显示键盘上的工具条。
     */
}



#pragma mark ---------------------设置分享--------------------


- (void)configUSharePlatforms
{
    /* 设置微信的appKey和appSecret */
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:@"wx054cc3541ada6efd" appSecret:@"3baf1193c85774b3fd9d18447d76cab0" redirectURL:@"http://www.zbomc.com"];
}




// 支持所有iOS系统
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    //6.3的新的API调用，是为了兼容国外平台(例如:新版facebookSDK,VK等)的调用[如果用6.2的api调用会没有回调],对国内平台没有影响
    //BOOL result = [[UMSocialManager defaultManager]  handleOpenURL:url sourceApplication:sourceApplication annotation:annotation];
    
    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url];
    if (!result) {
        // 其他如支付等SDK的回调
        
        [[[UIAlertView alloc] initWithTitle:@"==分享提示=="
                                    message:@"分享成功"
                           cancelButtonItem:nil
                           otherButtonItems:[RIButtonItem itemWithLabel:@"确定" action:^{
        }], nil] show];
    }
    return result;
}




- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url];
    if (!result) {
        // 其他如支付等SDK的回调
    }
    return result;
}




// 跳到指定页面
-(void)presentViewControllerWithPushInfo:(NSDictionary * )userInfo{
    
    GMWebViewController *pushNav =[[GMWebViewController alloc]init];
    pushNav.isPush = YES;
    self.window.rootViewController = pushNav;
    //    [self.window.rootViewController presentViewController:pushNav animated:YES completion:nil];
    
}








@end
